﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Peak.Core;
using Peak.Core.DataInterfaces;
using Peak.Web.Controllers.Services;
using SharpArch.Web.NHibernate;
using MvcContrib;

namespace Peak.Web.Controllers
{
  public class TeamController : BaseController
  {
    private readonly IUserRepository _userRepository;

    public TeamController(ISessionService sessionService, IUserRepository userRepository)
      :base(sessionService)
    {
      _userRepository = userRepository;
    }

    public ActionResult Index()
    {
      return View(_sessionService.Project.Users);
    }

    public ActionResult Add()
    {
      IList<User> users = _userRepository.GetAll();
      return View(users);
    }

    [AcceptVerbs(HttpVerbs.Post)]
    [Transaction]
    public ActionResult Add(int[] userIds)
    {
      Project project = _sessionService.Project;      
      foreach (int userId in userIds)
      {
        if (project.Users.FirstOrDefault(f => f.Id == userId) == null)
        {
          User user = _userRepository.Get(userId);
          project.Users.Add(user);
        }
      }
      return this.RedirectToAction(f => f.Index());
    }    

    [Transaction]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Remove(int[] userIds)
    {
      Project project = _sessionService.Project;
      foreach (int userId in userIds)
      {
        User user = project.Users.FirstOrDefault(f => f.Id == userId);
        project.Users.Remove(user);        
      }
      return this.RedirectToAction(f => f.Index());
    }
  }
}
